package org.example.objevent.executor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class EventExecutorFactory implements ThreadFactory {

	private final static AtomicInteger poolCounts = new AtomicInteger(0);

	private final ThreadGroup group;
	private final AtomicInteger threadNumber = new AtomicInteger(0);
	private final String namePrefix = "event";

	public EventExecutorFactory() {

		SecurityManager securityManager = System.getSecurityManager();

		group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();

		poolCounts.incrementAndGet();

	}

	public Thread newThread(Runnable r) {

		String name = namePrefix + "-" + threadNumber.getAndIncrement();

		Thread t = new Thread(group, r, name, 0);

		if (t.isDaemon()) {
			t.setDaemon(false);
		}

		if (t.getPriority() != Thread.NORM_PRIORITY) {
			t.setPriority(Thread.NORM_PRIORITY);
		}

		log.info("创建新线程:[已创建：{}, 新线程: {}]", threadNumber.get(), t);

		return t;

	}

}
